import { Dialog,I18Parse,CommonLang} from "@lowcode/jpaas-common-lib"
import formCodegenBusiness from '@/locales/lang/impl/form/formCodegenBusinessLang.js';
let lang = formCodegenBusiness;
let i18n=function (langKey,text) {
    return I18Parse.getI18Val(lang.formCodegenBusiness.edit2.pcFunction,langKey, text)
}
export default  {
  data(){
    return {
        /*commonJsLib:{
        name: "插入函数",
          children: [
            {name: "插入调用脚本", clickEvent: "insertInvokePcScript"},
            {name: "插入自定义查询", clickEvent: "insertPcCustomQuery"},
            {name: "插入第三方接口", clickEvent: "insertInvokePcInterface"},
            {name: "插入打开表单", clickEvent: "insertOpenFormScript"},
            {name: "AJAX请求(postJson)", clickEvent: "insertPostJson"},
            {name: "AJAX请求(get)", clickEvent: "insertGet"},
            {name: "AJAX请求(postForm)", clickEvent: "insertPostForm"},
            {name: "插入打开定制页面", clickEvent: "insertCustomForm"},
            {name: "插入打开VUE组件", clickEvent: "insertVueComponent"},
            {name: "插入打开列表", clickEvent: "insertOpenList"},
            {name: "插入打开对话框", clickEvent: "insertOpenDialog"},
          ]
        },*/
        commonJsLib:[
            {name: i18n('insertCallScript','插入调用脚本'), clickEvent: "insertInvokePcScript"},
            {name: i18n('insertCustomQuery','插入自定义查询'), clickEvent: "insertPcCustomQuery"},
            {name: i18n('insertInterface','插入第三方接口'), clickEvent: "insertInvokePcInterface"},
            {name: i18n('insertOpenForm','插入打开表单'), clickEvent: "insertOpenFormScript"},
            {name: i18n('insertCustomForm','插入打开定制页面'), clickEvent: "insertCustomForm"},
            {name: i18n('insertOpenList','插入打开列表'), clickEvent: "insertOpenList"},
            {name: i18n('insertOpenDialog','插入打开对话框'), clickEvent: "insertOpenDialog"},
        ],
      flowJsLib:{
        name:"流程函数",
        children:[
          {
            name:"启动流程",
            clickEvent:"startProcess"
          },
          {
            name:"保存草稿",
            clickEvent:"saveDraft"
          },
          {
            name:"通过界面启动流程",
            clickEvent:"openStartFlowDialog"
          },
        ]

      },
      tableJsLib: {
        name: "表格函数",
        children: [
          {
            name: "插入行统计函数",
            condition: "",
            clickEvent: "insertRowSummaryScript"
          },
          {
            name: "插入总统计函数",
            condition: "",
            clickEvent: "insertDrawSummaryScript"
          },
          {
            name: "插入控制编辑函数",
            condition: "mdl.rowEdit=='YES'",
            clickEvent: "insertActiveEditScript"
          },
          {
            name: "插入行点击事件",
            condition: "",
            clickEvent: "insertRowClick"
          },
          {
            name: "插入行双击事件",
            condition: "",
            clickEvent: "insertDoubleRowClick"
          },
          {
            name: "插入选择框配置函数",
            condition: "",
            clickEvent: "insertGetCheckboxPropsScript"
          },
          {
            name: "插入单元格合并函数",
            condition: "",
            clickEvent: "insertCustomCellScript"
          },
          {name: "插入选中的行", clickEvent: "insertSelectRows"},
          {name: "插入刷新表格", clickEvent: "insertRefreshData"},
          {name: "插入加载函数",clickEvent: "insertOnload"}]
      }



    }
  },
  methods:{
    i18n(name,text,key){
      return this.$ti18(name,text,"formCodegenBusiness",key);
    },
    /**
     *  插入脚本。
     * @param item
     */
    handInsertScript(item){
      this[item.clickEvent]();
    },
    insertScript(script){
      this.$refs.bodyScript.insertContent(script);
    },
    insertImportScript( script){
      this.$refs.javaCode.insertContent(script);
    },
    insertInvokePcScript() {
      var self_ = this;
      this.insertInvokeScript(function (script) {
        self_.insertScript(script);
      })
    },
    insertInvokeScript(callback) {
      Dialog.openInvokeScriptDialog({
        curVm: this,
        widthHeight: ['800px', '600px']
      }, function (self, data) {
        var ary = JSON.parse(data.params);
        var paramValue = self.getParamValue(ary, false);
        var tmp = paramValue.tmp;
        var strTmp = paramValue.strTmp;
        var str = "/**\n" +
            strTmp +
            " * @return " + data.descp + "\n" +
            " */\n";
        if (data.async) {
          str += "this.invokeScript(\"" + data.alias + "\"," + JSON.stringify(tmp) + ",function(data){\n";
          str += "   //data:{success:是否执行成功,message:提示信息,data:脚本返回数据}\n";
          str += "});"
        } else {
          str += "//rtn:{success:是否执行成功,message:提示信息,data:脚本返回数据}\n";
          str += "var rtn= this.invokeScriptPromise(\"" + data.alias + "\"," + JSON.stringify(tmp) + ");";
        }
        if (callback) {
          callback(str);
        }
      })
    },
    getParamValue(ary, isChild) {
      var tmp = {};
      var strTmp = "";
      for (var i = 0; ary && i < ary.length; i++) {
        var obj = ary[i];
        var paramType = obj.paramType;
        if (isChild) {
          strTmp += " *  @subParam ";
        } else {
          strTmp += " * @param ";
        }
        strTmp += obj.paramName + " " + obj.paramDescp + " " + obj.paramType + "\n";
        if (!paramType || paramType == 'string') {
          tmp[obj.paramName] = "";
        } else if (paramType == 'int') {
          tmp[obj.paramName] = 0;
        } else if (paramType == 'date') {
          tmp[obj.paramName] = null;
        } else if (paramType == 'boolean') {
          tmp[obj.paramName] = false;
        } else if (paramType == 'obj') {
          var child = obj.children;
          var paramValue = this.getParamValue(child, true);
          tmp[obj.paramName] = paramValue.tmp;
          strTmp += paramValue.strTmp;
        }
      }
      return {
        tmp: tmp,
        strTmp: strTmp
      };
    },
    insertCustomQuery(callback) {
      Dialog.openCustomDataDialog({
        curVm: this,
        widthHeight: ['800px', '600px']
      }, function (self, data) {
        var whereField = self.getWhereField(JSON.parse(data.whereField));
        var resultField = self.getResultField(JSON.parse(data.resultField));
        var str = "\n/**\n" +
            whereField.strTmp +
            " */ \n" +
            "this.invokeCustomQuery(\"" + data.key + "\"," + JSON.stringify(whereField.tmp) + ",function(data){\n" +
            "   //返回的数据 data:[" + resultField + "]\n" +
            "});";

        if (callback) {
          callback(str);
        }

      });
    },
    insertPcCustomQuery() {
      var self_ = this;
      this.insertCustomQuery(function (script) {
        self_.insertScript(script);
      })
    },
    insertOnload(){
      let script=`onload_(){}`;
      this.insertScript(script);
    },
    insertInvokePcInterface() {
      var self_ = this;
      this.insertInvokeInterface(function (script) {
        self_.insertScript(script);
      })
    },
    insertInvokeInterface(callback) {
      Dialog.openSysInterfaceDialog({
        curVm: this, max: true
      }, function (self, data) {
        var params = {};
        var strTmp = "";
        if ((data.apiDataType == 'form' || data.apiDataType == 'json') && data.apiBody) {
          //请求体参数配置
          strTmp += self.getInterfaceParams(params, 'bodys', '请求体', data.apiBody, data.apiDataType == 'json');
        }
        if (data.apiHeaders) {
          //请求头参数配置
          strTmp += self.getInterfaceParams(params, 'headers', '请求头', data.apiHeaders, false);
        }
        if (data.apiPathParams) {
          //请求路径参数配置
          strTmp += self.getInterfaceParams(params, 'pathParams', '路径参数', data.apiPathParams, false);
        }
        if (data.apiQuery) {
          //查询参数配置
          strTmp += self.getInterfaceParams(params, 'querys', '查询参数', data.apiQuery, false);
        }
        var str = "\n/**\n" +
            " 接口名称:" + data.apiName + "\n" +
            " 接口路径:" + data.apiPath + "\n" +
            strTmp +
            " */ \n" +
            "this.invokeInterface(\"" + (data.apiKey || data.apiId) + "\"," + JSON.stringify(params) + ",function(data){\n" +
            "   //data:接口返回数据\n" +
            "});";
        if (callback) {
          callback(str);
        }
      })
    },
    getInterfaceParams(rootParams, key, name, paramsStr, isJson) {
      var params = JSON.parse(paramsStr);
      if (isJson) {
        var getParams = function (array) {
          return array.filter(function (item) {
            if (item.paramType == 'object' || item.paramType == 'array') {
              item.children = getParams(item.children);
              return item.children.length > 0;
            } else {
              return item.paramSource == 'param';
            }
          })
        }
        let filterArr = getParams(params);
        if (filterArr.length > 0) {
          var getParamsValue = function (obj) {
            if (obj.paramType == 'object') {
              var paramsValue = {};
              for (var i = 0; i < obj.children.length; i++) {
                var item = obj.children[i];
                paramsValue[item.paramName] = getParamsValue(item);
              }
              return paramsValue;
            } else if (obj.paramType == 'array') {
              var paramsValue = [];
              for (var i = 0; i < obj.children.length; i++) {
                var item = obj.children[i];
                paramsValue.push(getParamsValue(item));
              }
              return paramsValue;
            } else {
              if (obj.paramType == 'number') {
                return 0;
              } else if (obj.paramType == 'boolean') {
                return false;
              } else {
                return "";
              }
            }
          }
          rootParams[key] = getParamsValue(filterArr[0]);
          return " @param " + key + " " + name + "\n";
        }
      } else {
        let filterArr = params.filter(item => item.paramSource == 'param');
        if (filterArr.length > 0) {
          rootParams[key] = {};
          filterArr.map(item => {
            rootParams[key][item.paramName] = "";
          });
          return " @param " + key + " " + name + "\n";
        }
      }
      return "";
    },
    insertOpenFormScript(){
      var config={
        curVm: this, widthHeight: ['900px', '600px'],
        data:{params:{}}
      };

      Dialog.openFormDialog(config,(res)=>{
        let script=`let self_=this;
            var conf={
                //表单标题
                title:"${res.name}",
                //表单方案别名
                alias:"${res.alias}",
                //主键
                pkId:"",
                //是否只读
                readOnly:false,
                parent:{},
                //open在“新页面”模式下打开表单的方式，'window'弹窗打开，不填或者其它则为新页面打开
                open:'window',
                //表单初始化数据
                params:{"key":"value"},
                destroy:function (action,data) {
                    //刷新表格
                    self_.loadData();
                }
            };
            this.showForm(conf);
            `;
        this.insertScript(script);
      })
    },
    insertPostJson(){
      let script=`
//插入postJson函数
let params={key:"",}
this.getAjax().postJson(url,params).then(res=>{})`;
      this.insertScript(script);
    },
    insertGet(){
      let script=`
//插入get函数,参数可以为空
let params={key:""}
this.getAjax().get(url,params).then(res=>{})`;
      this.insertScript(script);
    },
    insertPostForm(){
      let script=`
//插入get函数,参数可以为空
let params={key:""}
this.getAjax().postForm(url,params).then(res=>{})`;
      this.insertScript(script);
    },
    insertCustomForm(){

      var config={
        curVm: this, widthHeight: ['900px', '600px'],
      };
      Dialog.openCustomPageDialog(config,(res)=>{
        let json={};
        let paramDef=res.params || "[]";
        let paramsAry=JSON.parse(paramDef);
        for(let i=0;i<paramsAry.length;i++){
          let o=paramsAry[i];
          json[o.value]=o.label;
        }
        let str=JSON.stringify(json);

        let script=`let params=${str};
                this.openCustom("${res.alias}",params)`;
        this.insertScript(script);
      });
    },
    insertVueComponent(){
      let script=`var conf={
        //组件路径
        component:"modules/demo/DemoForm.vue",
        max:false,
        widthHeight:[  '800px',   '600px'],
        curVm: this,
        //参数
        data:{"user":{name:"老周"}}
    };
    this.openComponent(conf, function(action,data){
        console.info(action,data);
    })`;
      this.insertScript(script);
    },
    getParams(searchJson){
      let params={};
      if(!searchJson){
        return params;
      }
      let json=JSON.parse(searchJson);
      let aryJson=json.filter(item=>{
        return item.type=="income";
      });
      if(aryJson.length==0){
        return params;
      }
      for(let i=0;i<aryJson.length;i++){
        let obj=aryJson[i];
        var tabPre=obj.tablePre ? obj.tablePre +"." : "";
        var type=this.getType(obj.dataType);
        var val="Q_" + tabPre + obj.fieldName +"_" +type +"_" +obj.fieldOp;
        params[val]="";
      }
      return params;
    },
    getType(type){
      var typeObj={string:"S",number:"I",date:"D"};
      if(typeObj[type]){
        return typeObj[type];
      }
      return  "S";
    },
    objToQuery(obj){
      let ary=[];
      for(let key in obj){
        ary.push(key +"=" + obj[key])
      }
      return ary.join("&");
    },
    insertOpenDialog(){
      let self_=this;
      Dialog.openFormBoListDialog({
        curVm: this,
        data: {single: true, isDialog: 'YES',isDataGrant:true},
        widthHeight: ['1000px', '600px']
      }, function (self, data,pmtAlias) {
        var obj=data[0];
        let params={single:obj.multiSelect=="NO"};
        if(pmtAlias){
          params.pmtAlias=pmtAlias;
        }
        let searchJson=obj.searchJson;
        let objParams=self_.getParams(searchJson);
        objParams =Object.assign(params,objParams);
        let strParams=self_.objToQuery(objParams);

        var str = `/**
                    打开对话框：${obj.name} 
                     */
                    this.getDialog().dialog({key:"${obj.key}",params:"${strParams}",onload:function(){
                      this.$nextTick(() => {
                        let isDialog = this.formBoList.isDialog;
                        let isTreeDlg = this.formBoList.isTreeDlg;
                        let multiSelect = this.formBoList.multiSelect;
                        let idField = this.formBoList.idField;
                        setTimeout(() => {
                        let returnData=[];
                        if (isTreeDlg === 'YES') {
                           let ary=returnData.map(item=>item[idField])
                           this.$refs.rxTree.checkeds=ary;
                        } else if (isDialog === 'YES') {
                           this.selectedRows=returnData;
                           if (multiSelect){
                              this.selectedTable.dataSource=[...returnData]
                           }
                        }
                        });
                      });
                    }},
                    {curVm: this,max:${obj.isMax=="YES"},widthHeight:['${obj.width}px', '${obj.height}px']},function(data){
                        //data:对话框选择数据
                    })`;

        self.insertScript(str);
      })
    },
    insertOpenList(){
      let self_=this;
      Dialog.openFormBoListDialog({
        curVm: this,
        data: {single: true, isDialog: 'NO',isDataGrant:true},
        widthHeight: ['1000px', '600px']
      }, function (self, data,pmtAlias) {

        var obj=data[0];

        let params={single:obj.multiSelect=="NO"};
        if(pmtAlias){
          params.pmtAlias=pmtAlias;
        }
        let searchJson=obj.searchJson;
        let objParams=self_.getParams(searchJson);
        objParams =Object.assign(params,objParams);
        let strParams=self_.objToQuery(objParams);

        var str = `/**
                    打开列表：${obj.name} 
                     */
                    this.getDialog().dialog({key:"${obj.key}",params:"${strParams}"},
                    {curVm: this,max:${obj.isMax=="YES"},widthHeight:['${obj.width}px', '${obj.height}px']},function(data){
                        //data:对话框选择数据
                    })`;
        self.insertScript(str);
      })
    },
    startProcess(){
      let script=`let json={"表单别名":"表单JSON数据,是JSON对象"}
    let params={
        formJson:JSON.stringify(json),
        //草稿实例
        instId:"",
        defKey:"流程定义KEY"
    }
    this.startProcess(params).then(res=>{})`;
      this.insertScript(script);
    },
    saveDraft(){
      let script=`let json={"表单别名":"表单JSON数据,是JSON对象"}
    let params={
        formJson:JSON.stringify(json),
        //草稿实例
        instId:"",
        defKey:"流程定义KEY"
    }
    this.saveDraft(params).then(res=>{})`;
      this.insertScript(script);
    },
    openStartFlowDialog(){
      let script=`this.openStartFlowDialog("流程别名","表单主键",{表单数据可以为null},function(action,data){
    })`;
      this.insertScript(script);
    },
    insertCustomCellScript(){
      let script=`customCell(field,row,index,data){
        //field:列名 row:行数据,index:行下标,data:表格对象
        //this.getRowSpan(field,row,index,data.data) :获取当前列可以纵向合并的数量
        //this.getColSpan(field,row,data) :获取当前列可以横向合并的数量
        const obj = {
          attrs: {},
        };
        return obj;
      }`;
      this.insertScript(script);
    },
    insertRowSummaryScript(){
      let script=`rowSummaryFun(record){
        //返回一行数据到子节点
        return {};
      }`;
      this.insertScript(script);
    },
    insertDrawSummaryScript(){
      let script=`drawSummaryFun(e){
        //循环数组赋值e.cellHtml来展示统计行内容
        //e:{sender,data,column,field,cellHtml,width}
        }`;
      this.insertScript(script);
    },
    insertActiveEditScript(){
      let script=`activeEditFun(col,row){
        //返回true/false，来确定单元格是否可编辑
        //col:{column,index} row:{record,index}
        }`;
      this.insertScript(script);
    },
    insertGetCheckboxPropsScript(){
      let script=`getCheckboxPropsMethod(record){
        return ({
                    props: {
                        disabled: true
                    }
                })
        }`;
      this.insertScript(script);
    },
    insertRowClick(){
      let script=`//插入行点击函数
handRowClick(record, index){
}`;
      this.insertScript(script);
    },
    insertDoubleRowClick(){
      let script=`
//插入行双击函数
handRowDblClick(record,index){
}`;
      this.insertScript(script);
    },
    insertSelectRows(){
      let script=`this.$refs.table.getSelectedRows()`;
      this.insertScript(script);
    },
    /**
     * 插入刷新方法。
     */
    insertRefreshData(){
      let script=`this.loadData()`;
      this.insertScript(script);
    },
    //获取自定义查询返回字段
    getResultField(ary) {
      var str = "{";
      for (var i = 0; ary && i < ary.length; i++) {
        if (i > 0) {
          str += ",";
        }
        var obj = ary[i];
        str += obj.fieldName;
      }
      str += "}";
      return str;
    },
    //获取自定义查询条件字段
    getWhereField(ary) {
      var tmp = {};
      var strTmp = " * @param ";
      for (var i = 0; ary && i < ary.length; i++) {
        var obj = ary[i];
        var paramType = obj.columnType;
        strTmp += obj.fieldName + " " + paramType + "\n";
        tmp[obj.fieldName] = "";
      }
      return {
        tmp: tmp,
        strTmp: strTmp
      };
    },
  }

}